import { useBoolean } from 'ahooks';
import { Form, Modal } from 'antd';
import React, { useRef } from 'react';
import request from '@/utils/request';
import ProcessForm from './ProcessForm';
import { GlobalFormLayout, MiddleFormLayout, SmallFormLayout } from '@/layouts/Form';
import ProcessCreateStepForm from './ProcessCreateStepForm';

function EditProcessModal({ visible, onClose, data, form, onOk }) {
  const { processId } = data;
  const [submitting, { setTrue: onSubmitting, setFalse: finishSubmit }] = useBoolean(false);
  const isEdit = !!processId;
  const formRef = useRef();

  function handleSubmit() {
    const form = formRef.current;
    form.validateFields((err, _) => {
      if (!err) {
        const data = form.getFieldsValue();
        onSubmitting();
        if (isEdit) {
          request
            .post('/process/updateProcess', { data })
            .then(onOk)
            .finally(() => finishSubmit());
        } else {
          request
            .post('/process/createProcess', { data })
            .then(onOk)
            .finally(() => finishSubmit());
        }
      }
    });
  }

  return (
    <Modal
      title={isEdit ? '编辑流程' : '新增流程'}
      width={isEdit ? 520 : 900}
      visible={visible}
      onCancel={onClose}
      destroyOnClose
      confirmLoading={submitting}
      onOk={() => handleSubmit()}
    >
      <Form {...(isEdit ? GlobalFormLayout : MiddleFormLayout)}>
        {isEdit ? (
          <ProcessForm ref={formRef} form={form} {...data} />
        ) : (
          <ProcessCreateStepForm ref={formRef} form={form} {...data} />
        )}
      </Form>
    </Modal>
  );
}

export default Form.create()(EditProcessModal);
